/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-03-18     desktop       the first version
 */

#include <all_code.h>

/*  导入log工具 */
#define DBG_TAG "time_device.c"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>


rt_device_t foot_hw_time_dev; /* 定 时 器 设 备 句 柄 */
rt_device_t hand_hw_time_dev; /* 定 时 器 设 备 句 柄 */
rt_hwtimer_mode_t mode; /* 定 时 器 模 式 */
rt_uint32_t freq = 10000; /* 计 数 频 率 */
rt_hwtimerval_t foot_timeout_s; /* 定 时 器 超 时 值 */
rt_hwtimerval_t hand_timeout_s; /* 定 时 器 超 时 值 */

/* 脚部   定 时 器 超 时 回 调 函 数 */
static rt_err_t foot_time_out_cb(rt_device_t dev, rt_size_t size)
{
    if(foot_scheduling_flag <=3)
    {
        foot_scheduling_flag ++;
        rt_sem_release(&foot_sch_semaphore);
    }
    else if(foot_scheduling_flag >3)
    {
        foot_scheduling_flag = 1;
        rt_sem_release(&foot_sch_semaphore);
    }
    return 0;
}

/* 脚部   定 时 器 超 时 回 调 函 数 */
static rt_err_t hand_time_out_cb(rt_device_t dev, rt_size_t size)
{

    if(hand_scheduling_flag == 1)
    {
        rt_sem_release(&hand_sch_semaphore);
    }

    else if(hand_scheduling_flag == 2)
    {
        LOG_E("手部1s停止完成\t\n");
        hand_scheduling_flag = 3;
        rt_sem_release(&hand_sch_semaphore);
    }

    else if(hand_scheduling_flag == 4)
    {
        rt_sem_release(&hand_sch_semaphore);
    }

    else if(hand_scheduling_flag == 5)
    {
        LOG_E("手部1s停止完成\t\n");
        hand_scheduling_flag = 6;
        rt_sem_release(&hand_sch_semaphore);
    }

    else if(hand_scheduling_flag == 7)
    {
        rt_sem_release(&hand_sch_semaphore);
    }
    return 0;
}

void time_device_init(void)
{
    /* 查 找 定 时 器 设 备 */
    foot_hw_time_dev = rt_device_find(FOOT_HWTIMER_DEV_NAME);
    hand_hw_time_dev = rt_device_find(HAND_HWTIMER_DEV_NAME);
    /* 以 读 写 方 式 打 开 设 备 */
    rt_device_open(foot_hw_time_dev, RT_DEVICE_OFLAG_RDWR);
    rt_device_open(hand_hw_time_dev, RT_DEVICE_OFLAG_RDWR);
    /* 设 置 超 时 回 调 函 数 */
    rt_device_set_rx_indicate(foot_hw_time_dev, foot_time_out_cb);
    rt_device_set_rx_indicate(hand_hw_time_dev, hand_time_out_cb);
    /* 设 置 计 数 频 率(默 认1Mhz或 支 持 的 最 小 计 数 频 率) */
    rt_device_control(foot_hw_time_dev, HWTIMER_CTRL_FREQ_SET, &freq);
    rt_device_control(hand_hw_time_dev, HWTIMER_CTRL_FREQ_SET, &freq);
    /* 设 置 模 式 为 周 期 性 定 时 器 */
    mode = HWTIMER_MODE_PERIOD;
    rt_device_control(foot_hw_time_dev, HWTIMER_CTRL_MODE_SET, &mode);
    rt_device_control(hand_hw_time_dev, HWTIMER_CTRL_MODE_SET, &mode);

    //启动定时器,这里不用启动，在线程里会启动
    //rt_device_write(foot_hw_time_dev, 0, &foot_timeout_s, sizeof(foot_timeout_s));

}
